package com.cooba.broadCastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Process;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.application.MyApplication;
import com.cooba.bean.MacBean;
import com.cooba.dialog.ComfirmDialog;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2015/12/14.
 * 广播服务监听
 */
public class MyReceiver1 extends BroadcastReceiver {
    private static int lastType = -1;
    private Context mContext;
    private ComfirmDialog dialog;
    public static final String WIFI_STATE_CHANGED = "android.net.wifi.WIFI_STATE_CHANGED";
    private WifiManager manger;
    private JSONObject json;
    private boolean isfirst = true;
    private String lastBssid = "";
    private Boolean lastIsSuccess=false;
    private MacBean macbean;

    @Override
    public void onReceive(Context context, Intent intent) {
        // log.debug("网络状态改变");
        mContext = context;
        String action = intent.getAction();
        Log.d("wei", "网络状态改变 action=" + action + " lastType=" + lastType + ",lastbssid=" + lastBssid);
        // 获得网络连接服务
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connManager.getActiveNetworkInfo();
        NetworkInfo wifiNetInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        WifiManager mWifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = mWifi.getConnectionInfo();
        if (info == null || !connManager.getBackgroundDataSetting()) {
            Log.d("wei", "您的网络连接已中断");
            lastType = -1;
        } else {
            int netType = info.getType();
            if (netType != lastType) {//网络类型变化
                if (info.isConnected()) {
                    //delay 5seconds

                    if (wifiNetInfo.isConnected()) {
                        lastBssid = wifiInfo.getBSSID();

                    }
                    Log.d("wei", "new connection was create...type:" + info.getTypeName() + " status"
                            + info.getDetailedState());
                    requestData();
                } else {
                    //delay 5seconds
                    Log.d("wei", "the connection was broken...type:" + info.getTypeName() + " status"
                            + info.getDetailedState());
                }
                lastType = netType;
            } else if (netType == 1) {
                if (wifiNetInfo.isConnected()) {
                    if (!wifiInfo.getBSSID().equals(lastBssid)) {
                        Log.d("wei", "wifi connection change...");
                        lastBssid = wifiInfo.getBSSID();
                        requestData();
                    }
                }

            }
        }
    }

    private HttpUtils httpUtils;

    private void requestData() {
        httpUtils = new HttpUtils();
        httpUtils.configDefaultHttpCacheExpiry(0);
        httpUtils.configCurrentHttpCacheExpiry(0);
        httpUtils.send(HttpRequest.HttpMethod.GET, "http://a.cooba.cc/macmark.json", null, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "车载数据获取失败");

                MyApplication application = MyApplication.getMyApplication();
                if (application.getIsStart()) {
                    application.setIsStart(false);
                } else if (lastIsSuccess){
                    dialog=new ComfirmDialog(mContext, R.style.custom_dialog, R.layout.dialog_comfirm, new ComfirmDialog.DialogListener() {
                        @Override
                        public void comfirm() {
                            Intent i = mContext.getPackageManager()
                                    .getLaunchIntentForPackage(mContext.getPackageName());
                            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            mContext.startActivity(i);
                            Process.killProcess(Process.myPid());

                        }
                    });
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.setCancelable(false);
                    android.view.Window window = dialog.getWindow();
                    window.setGravity(Gravity.CENTER);
                    dialog.show();
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "车载数据获取成功" + responseInfo.result);
                //                    json = new JSONObject(responseInfo.result);
//                    String mac = json.get("MAC").toString();
//                    String macName=json.get("factory").toString();

                macbean=new Gson().fromJson(responseInfo.result, MacBean.class);
                MyApplication application = MyApplication.getMyApplication();
                application.setIsInCar(true);
                application.setMac(macbean.getMAC());
                application.setFactoryName(macbean.getFactory());
                lastIsSuccess=true;
                if (application.getIsStart()) {
                    application.setIsStart(false);
                } else {
                    dialog=new ComfirmDialog(mContext, R.style.custom_dialog, R.layout.dialog_comfirm, new ComfirmDialog.DialogListener() {
                        @Override
                        public void comfirm() {
                            Intent i = mContext.getPackageManager()
                                    .getLaunchIntentForPackage(mContext.getPackageName());
                            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            mContext.startActivity(i);
                            Process.killProcess(Process.myPid());

                        }
                    });
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.setCancelable(false);
                    android.view.Window window = dialog.getWindow();
                    window.setGravity(Gravity.CENTER);
                    dialog.show();
                }
            }
        });
    }

}

